<template>
  <div class="container">
    <el-form ref="dataForm" :model="conModel" label-width="72px" class="search_content" size="mini">
      <el-row :gutter="24">
        <el-col :span="4" class="common_input">
          <el-form-item label="账期:">
            <el-select v-model="conModel.SearchKey" clearable placeholder="请选择账期">
              <el-option
                v-for="item in listAccPeriod"
                :key="item.val"
                :label="item.val"
                :value="item.val"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_input">
          <el-form-item label="结算状态:">
            <el-select v-model="conModel.State" clearable placeholder="请选择结算状态">
              <el-option key="0" label="全部" value="" />
              <el-option key="1" label="已创建" value="1" />
              <el-option key="2" label="待执行" value="2" />
              <el-option key="3" label="结算中" value="3" />
              <el-option key="4" label="结算完成" value="4" />
              <el-option key="5" label="执行失败" value="5" />
              <el-option key="6" label="撤回" value="6" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_picker">
          <el-form-item label="开始时间:">
            <el-date-picker
              v-model="conModel.StartTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              alue-format="yyyy-MM-dd HH:mm"
              placeholder="请选择开始时间"
              size="mini"
              class="search_common_picker"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_picker">
          <el-form-item label="结束时间:">
            <el-date-picker
              v-model="conModel.EndTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              alue-format="yyyy-MM-dd HH:mm"
              placeholder="请选择结束时间"
              size="mini"
              class="search_common_picker"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1" class="common_query">
          <el-button size="mini" @click="getList('search')">
            <span>查询</span>
          </el-button>
        </el-col>
        <div class="common_right_btn common_query">
          <el-col :span="1">
            <el-button size="mini" @click="batchPopup('','2')" class="batch_btn">
              批量抄表
            </el-button>
          </el-col>
        </div>
      </el-row>
    </el-form>
    <p class="batch_tips">提示: 处于已创建状态的任务可修改,其他状态不可修改</p>
    <div class="table_content">
      <el-table
        v-loading="listLoading"
        :data="listMeterTask"
        fit
        style="width: 100%;"
        :stripe="true"
      >
        <el-table-column align="center" label="开始时间" width="160px">
          <template slot-scope="scope">
            {{ scope.row.p.StartTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="结束时间" width="160px">
          <template slot-scope="scope">
            {{ scope.row.p.EndTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="账期">
          <template slot-scope="scope">
            {{ scope.row.p.AccPeriod }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="管输气价格类型">
          <template slot-scope="scope">
            {{ PriceType(scope.row.p.PriceType1) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格方案">
          <template slot-scope="scope">
            {{ scope.row.p.PriceNo1 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="铭牌号">
          <template slot-scope="scope">
            <el-tooltip class="block_content_item" effect="light" :content="getBarCode(scope.row.p.BalanceParam)" placement="bottom" popper-class="test_tooltip">
              <span class="block_content">{{ getBarCode(scope.row.p.BalanceParam) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" label="表计数量">
          <template slot-scope="scope">
            {{ scope.row.p.MeterCount }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="结算状态">
          <template slot-scope="scope">
            {{ BalanceState(scope.row.p.BalanceState) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="执行进度">
          <template slot-scope="scope">
            {{ scope.row.p.Progress }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="400px">
          <template slot-scope="{row}">
            <span class="common_operation common_operation_2" @click="resulePopup(row)">查看结果</span>
            <span class="common_operation" @click="DeleteBatchBalanceTaskPopup(row)">删除</span>
            <span v-show="row.p.BalanceState === 1" class="common_operation" @click="EditBatchBalanceTask(row)">编辑</span>
            <span class="common_operation" @click="executeTasksPopup(row,'6')">撤销</span>
            <span class="common_operation common_operation_2" @click="executeTasksPopup(row,'2')">执行任务</span>
            <!-- <span class="common_operation common_operation_2" @click="executeTasks(row,'2')">重新执行</span> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" class="my_pagination" :total="total" :PageIndex.sync="Parameter.PageIndex" :PageSize.sync="Parameter.PageSize" @pagination="getList" />

    <el-dialog title="批量抄表" :visible.sync="dialogFormBatch" class="newel-dialog common_add_edit_popup_two batch_popup">
      <div class="el-dialog__body">
        <el-form ref="dataForm_Batch" :rules="rulesBatch" :model="temp" class="demo-ruleForm" label-width="130px" style="width: 100%; margin:0 auto;">
          <el-row :gutter="24">
            <el-col :span="9" :offset="1">
              <div class="grid-content bg-purple">
                <el-form-item label="结果计入账期:" prop="AccPeriod">
                  <el-select v-model="temp.AccPeriod" clearable placeholder="请选择结果计入账期">
                    <el-option
                      v-for="item in listAccPeriod"
                      :key="item.val"
                      :label="item.val"
                      :value="item.val"
                    />
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="grid-content bg-purple">
                <el-form-item label='管输气价格类型:' prop="PriceType1">
                  <el-select v-model="temp.PriceType1" clearable placeholder="请选择">
                    <el-option key="1" label="指定价格方案" value="1" />
                    <el-option key="2" label="自定义价格数据" value="2" />
                    <el-option key="3" label="系统方案" value="3" />
                  </el-select>
                </el-form-item>
                <el-form-item label='管输气价格方案:' prop="PriceNo1" v-show="show_1">
                  <el-select v-model="temp.PriceNo1" clearable placeholder="请选择管输气价格方案">
                    <el-option
                      v-for="item in listPricePlan"
                      :key="item.PriceNo"
                      :label="item.p.PriceName"
                      :value="item.p.PriceNo"
                    />
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" v-show="show_2">
            <el-col :span="7" :offset="1">
              <div class="grid-content bg-purple">
                <el-form-item label="价格1:" prop="Price1" class="price">
                  <el-input v-model="temp.PriceParam1.Price1" type="text" />
                </el-form-item>
                <el-form-item label="价格2:" prop="Price2" class="price">
                  <el-input v-model="temp.PriceParam1.Price2" type="text" />
                </el-form-item>
                <el-form-item label="价格3:" prop="Price3" class="price">
                  <el-input v-model="temp.PriceParam1.Price3" type="text" />
                </el-form-item>
                <el-form-item label="价格4:" prop="Price4" class="price">
                  <el-input v-model="temp.PriceParam1.Price4" type="text" />
                </el-form-item>
                <el-form-item label="价格5:" prop="Price5" class="price">
                  <el-input v-model="temp.PriceParam1.Price5" type="text" />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="7">
              <div class="grid-content bg-purple">
                <el-form-item label="阶梯1:" prop="Ladder1" class="price">
                  <el-input v-model="temp.PriceParam1.Ladder1" type="text" />
                </el-form-item>
                <el-form-item label="阶梯2:" prop="Ladder2" class="price">
                  <el-input v-model="temp.PriceParam1.Ladder2" type="text" />
                </el-form-item>
                <el-form-item label="阶梯3:" prop="Ladder3" class="price">
                  <el-input v-model="temp.PriceParam1.Ladder3" type="text" />
                </el-form-item>
                <el-form-item label="阶梯4:" prop="Ladder4" class="price">
                  <el-input v-model="temp.PriceParam1.Ladder4" type="text" />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <p class="batch_title_pupop">表计信息</p>
        <el-button class="sel_btn" @click="selMeterPopup()">选择表计</el-button>
        <hr class="common_popup_border_bottom">
        <div class="table_content">
          <el-table
            v-loading="listLoading"
            :data="listMeter"
            fit
            style="width: 100%;"
            :stripe="true"
            height="450"
          >
            <el-table-column align="center" label="IC卡卡号">
              <template slot-scope="scope">
                {{ scope.row.CardNo }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="铭牌号">
              <template slot-scope="scope">
                {{ scope.row.BarCode }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="客户名称">
              <template slot-scope="scope">
                {{ scope.row.CustomerName }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="计量点">
              <template slot-scope="scope">
                {{ scope.row.Address }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="上次抄表截止时间" width="160px">
              <template slot-scope="scope">
                {{ scope.row.LastBalanceEndTime | dateFormat }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="上次抄表读数(m³)" width="150px">
              <template slot-scope="scope">
                {{ scope.row.LastReading }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="截止时间" width="160px">
              <template slot-scope="scope">
                {{ scope.row.BalanceEndTime }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="本次抄表读数(m³)" width="150px">
              <template slot-scope="scope">
                {{ scope.row.Reading }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="{row}">
                <span class="common_operation" @click="deleteMeterParams(row)">删除</span>
                <span class="common_operation" @click="setMeterParamsPopup(row)">设置</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="add_edit_btn cancel" @click="dialogFormBatch = false">
          取消
        </el-button>
        <el-button class="add_edit_btn determine" @click="AddBatchBalanceTask()">
          创建任务
        </el-button>
      </div>
    </el-dialog>

    <!-- 选择表计 -->
    <el-dialog title="选择表计" :visible.sync="dialogFormMeterSel" class="newel-dialog sel_meter_popup ">
      <div class="el-dialog__body">
        <el-form :model="conModelMeterSel" label-width="72px" size="mini" class="search_content">
          <el-col :span="4" class="common_input">
            <el-form-item label="铭牌号:">
              <el-input v-model="conModelMeterSel.BarCode" clearable placeholder="请输入铭牌号" @keyup.enter.native="GetMeterInfoSel('search')" />
            </el-form-item>
          </el-col>
          <el-col :span="4" class="common_input">
            <el-form-item label="客户名称:">
              <el-input v-model="conModelMeterSel.Name" clearable placeholder="请输入客户名称" @keyup.enter.native="GetMeterInfoSel('search')" />
            </el-form-item>
          </el-col>
          <el-col :span="1" class="common_query">
            <el-button size="mini" @click="GetMeterInfoSel('search')">
              查询
            </el-button>
          </el-col>
        </el-form>
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="listMeterSel"
          fit
          style="width: 100%;"
          :stripe="true"
          >
          <el-table-column align="center" label="IC卡卡号">
            <template slot-scope="scope">
              {{ scope.row.CardNo }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="铭牌号">
            <template slot-scope="scope">
              {{ scope.row.BarCode }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="客户名称">
            <template slot-scope="scope">
              {{ scope.row.CustomerName }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="计量点">
            <template slot-scope="scope">
              {{ scope.row.Address }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="{row}">
              <span class="common_operation" @click="addMeterItem(row)">添加</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination  v-show="totalMeterSel>0" :total="totalMeterSel" :PageIndex.sync="MeterSel.PageIndex" :PageSize.sync="MeterSel.PageSize" @pagination="GetMeterInfoSel" />
        <div slot="footer" class="dialog-footer">
          <el-button class="return_btn" @click="dialogFormMeterSel = false">
            返回
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 设置单个抄表数据 -->
    <el-dialog title="设置抄表数据" :visible.sync="dialogFormMeterParams" class="newel-dialog common_add_edit_popup_one">
      <div class="el-dialog__body">
        <el-form ref="dataForm"  :model="tempMeterParams" class="demo-ruleForm common_popup" label-width="114px">
          <el-row :gutter="24">
            <el-col :span="15" :offset="4">
              <div class="grid-content bg-purple">
                <el-form-item label="上次读数:" prop="LastReading">
                  <el-input v-model="tempMeterParams.LastReading" type="text" placeholder="请输入账册名称" />
                </el-form-item>
                <el-form-item label="上次截止时间:" prop="LastBalanceEndTime">
                  <el-date-picker
                    v-model="tempMeterParams.LastBalanceEndTime"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    alue-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择上次抄表截止时间"
                    size="mini"
                    class="popup_common_picker"
                  />
                </el-form-item>
                <el-form-item label="本次读数:" prop="Reading">
                  <el-input v-model="tempMeterParams.Reading" type="text" />
                </el-form-item>
                <el-form-item label="本次截止时间:" prop="BalanceEndTime">
                  <el-date-picker
                    v-model="tempMeterParams.BalanceEndTime"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm"
                    alue-format="yyyy-MM-dd HH:mm"
                    placeholder="请选择截止时间"
                    size="mini"
                    class="popup_common_picker"
                  />
                </el-form-item>
              </div>
            </el-col>

          </el-row>
        </el-form>
        <hr class="common_popup_border_bottom">
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="add_edit_btn cancel" @click="dialogFormMeterParams = false">
          取消
        </el-button>
        <el-button class="add_edit_btn determine" @click="editMeterParams()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 查看结果 -->
    <el-dialog title="查看结果" :visible.sync="dialogFormResult" class="newel-dialog sel_meter_popup result_popup">
      自定义价格数据: {{ priceText }}
      <div class="el-dialog__body">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="listResult"
          fit
          style="width: 100%;"
          :stripe="true"
          :height="520"
          >
          <el-table-column align="center" label="客户名称">
            <template slot-scope="scope">
              {{ scope.row.CustomerName }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="铭牌号">
            <template slot-scope="scope">
              {{ scope.row.BarCode }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="计量点">
            <template slot-scope="scope">
              {{ scope.row.Address }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="结果说明">
            <template slot-scope="scope">
              {{ scope.row.Message }}
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button class="return_btn" @click="dialogFormResult = false">
            返回
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 撤销 执行任务 -->
    <el-dialog
      :visible.sync="dialogVisibleExecute"
      class="common_delete_popup"
      :modal-append-to-body="false"
    >
      <div slot="title" class="header-title">
        <span class="title-age">提示</span>
      </div>
      <span class="delete_tips">{{ tasksText}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel" @click="dialogVisibleExecute = false">取消</el-button>
        <el-button class="delete" @click="executeTasks()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 删除 -->
    <el-dialog
      :visible.sync="dialogVisibleTaskDelete"
      class="common_delete_popup"
      :modal-append-to-body="false"
    >
      <div slot="title" class="header-title">
        <span class="title-age">提示</span>
      </div>
      <span class="delete_tips">是否进行删除?</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel" @click="dialogVisibleTaskDelete = false">取消</el-button>
        <el-button class="delete" @click="DeleteBatchBalanceTask()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { GetMeterInfo, GetPricePlan, AddBatchBalanceTask, GetLatestBalanceFee, GetBatchBalanceTask, DeleteBatchBalanceTask, GetMeterInfoByID, GetLatestData} from '@/api/basics'
import moment from 'moment'

// 排序 从小到大
function compare(a, b) {
  const MeterIdA = a.MeterId
  const MeterIdB = b.MeterId
  let comparison = 0;
  if (MeterIdA > MeterIdB) {
    comparison = 1;
  } else if (MeterIdA < MeterIdB) {
    comparison = -1;
  }
  return comparison;
}

export default {
  name: 'BatchSettle',
  components: {
    Pagination
  },
  data() {
    return {
      Parameter: {
        PageSize: 10,
        PageIndex: 1,
        OrderBy: 'Id',
        isDesc: true
      },
      conModel: {
        SearchKey: '',
        State: '',
        StartTime: '',
        EndTime: ''
      },
      conModelCopy: {},
      // 选择表计数据
      MeterSel: {
        PageSize: 10,
        PageIndex: 1,
        OrderBy: 'MeterId',
        isDesc: true
      },
      conModelMeterSel: {
        BarCode: '',
        Name: ''
      },
      conModelMeterSelCopy: {},
      listMeterSel: [],
      totalMeterSel: 0,
      dialogFormMeterSel: false,
      // 批量抄表
      temp: {
        Id: 0,
        BalanceType: 2, // 结算类型 1后付费2预付费
        AccPeriod: '', // 账期
        PriceType1: '', // 管输气价格类型
        PriceNo1: '', // 管输气指定的价格方案编号
        PriceParam1: { // 管输气自定义的价格参数
          Price1: '',
          Price2: '',
          Price3: '',
          Price4: '',
          Price5: '',
          Ladder1: '',
          Ladder2: '',
          Ladder3: '',
          Ladder4: ''
        },
        MeterCount: '', // 表计数量
        BalanceParam: '', // 结算参数  添加的表计信息1已创建2待执行3结算中4结算完成5执行失败6已撤销
        BalanceState: '', // 结算状态 
      },
      // 设置单个抄表数据
      tempMeterParams: {
        MeterId: '',
        CardNo: '',
        BarCode: '',
        CustomerName: '',
        Address: '',
        LastReading: '',
        Reading: '',
        LastBalanceEndTime: '',
        BalanceEndTime: ''
      },
      // 执行抄表任务2 撤销6 重新执行 AddBatchBalanceTask
      tempTasks: {

      },
      tasksText: '',
      // 删除任务
      taskDelete: '',
      listLoading: false,
      dialogFormBatch: false, // 批量抄表
      dialogFormMeterParams: false, // 设置单个抄表数据
      dialogVisibleExecute: false, // 撤销任务
      dialogVisibleTaskDelete: false, // 删除任务
      dialogFormResult: false, // 查看结果
      listResult: [], // 查看结果
      priceText: '', // 自定义价格数据
      list: [],
      total: 0,
      listPricePlan: [], // 价格方案
      rowInfo: [], // 基础信息
      listMeterPopup: [], // 表计信息
      listMeter: [], // 批量抄表的表计信息
      listMeterTask: [], // 抄表任务
      show_1: false, // 管输气价格方案 批量
      show_2: false, // 管输气自定义价格 批量
      listAccPeriod: [], // 结果入账期近六个月
      timer: null, // 定时器
      // 批量抄表
      rulesBatch: {
        AccPeriod: [
          { required: true, message: '请选择结果计入账期', trigger: 'change' }
        ],
        PriceType1: [
          { required: true, message: '请选择管输气价格类型', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    // 管输气类型 批量
    'temp.PriceType1': {
      handler(val) {
        let dialog = document.getElementsByClassName("el-dialog")[1]
        if (val == 3 || val == '') {
          this.show_1 = false
          this.show_2 = false
          dialog.style.height = '730px';
        } else if (val == 1) {
          this.show_1 = true
          this.show_2 = false
          dialog.style.height = '770px';
        } else if (val == 2) {
          this.show_1 = false
          this.show_2 = true
          dialog.style.height = '950px';
        }
      }
    }
  },
  mounted() {
    this.timer = setInterval(() => {
      this.getList('time')
    }, 30000)
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  created() {
    this.getList()
    this.listAccPeriod = [ ]
    // 结果计入账期
    for (var i = 0; i < 6; i++) {
      this.listAccPeriod.push({
        index: 0,
        val: moment(new Date()).subtract(i, 'months').format('YYYYMM')
      })
    }
  },
  methods: {
    // 价格方案
    GetPricePlan() {
      const Parameter = {
        PageSize: 99999,
        PageIndex: 1,
        OrderBy: 'BuildTime',
        isDesc: true
      }
      GetPricePlan(Parameter).then(res => {
        this.listPricePlan = res.Data
      })
    },
    PriceType(type) {
      switch (type) {
        case 1:
          return '指定价格方案'
        case 2:
          return '自定义价格数据'
        case 3:
          return '系统方案'
        case null:
          return '暂无状态'
      }
    },
    // 批量抄表弹窗
    batchPopup() {
      this.resetTemp()
      let dialog = document.getElementsByClassName("el-dialog")[1]
      dialog.style.height = '730px';
      this.show_1 = false
      this.show_2 = false
      this.dialogFormBatch = true
      this.listMeter = []
      this.listAccPeriod = []
      // 结果计入账期
      for (var i = 0; i < 6; i++) {
        this.listAccPeriod.push({
          index: 0,
          val: moment(new Date()).subtract(i, 'months').format('YYYYMM')
        })
      }
      this.GetPricePlan()
      this.$nextTick(() => {
        this.$refs['dataForm_Batch'].clearValidate()
      })
    },

    // 选择表计
    selMeterPopup() {
      this.dialogFormMeterSel = true
      this.MeterSel = {
        PageSize: 10,
        PageIndex: 1,
        OrderBy: 'MeterId',
        isDesc: true
      }
      this.conModelMeterSel = {
        BarCode: '',
        Name: ''
      }
      this.conModelMeterSelCopy = {}
      this.GetMeterInfoSel()
    },
    // 选择表计数据
    GetMeterInfoSel(init) {
      if (init === 'search') {
        this.MeterSel.PageIndex = 1
        this.conModelMeterSelCopy = {}
      }
      if (this.conModelMeterSel.BarCode.trim() !== '' && init === 'search') {
        this.conModelMeterSelCopy.BarCode = this.conModelMeterSel.BarCode.trim()
      }
      if (this.conModelMeterSel.Name.trim() !== '' && init === 'search') {
        this.conModelMeterSelCopy.Name = this.conModelMeterSel.Name.trim()
      }
      this.listLoading = true
      let Parameter = {
        ...this.MeterSel,
        ...this.conModelMeterSelCopy,
        DivideType: 0
      }
      GetMeterInfo(Parameter).then(res => {
        this.listMeterSel = res.Data
        this.totalMeterSel = res.Total
        this.listLoading = false
      })
    },
    // 添加表计信息
    addMeterItem(row) {
      // 表计ID MeterId 本次读数Reading  上次读数LastReading 上次截止时间LastBalanceEndTime 本次抄表的截止时间BalanceEndTime
      let Parameter = {
        MeterId: row.MeterId
      }
      
      GetLatestBalanceFee(Parameter).then(res => {
        let Parameter = {
          CommNo: row.CommNo,
          EndTime: moment().format('YYYY-MM-DD HH:mm')
        }
        GetLatestData(Parameter).then(resp => {
          let Reading = 0
          if (resp.State === 'success' && resp.Data !== undefined) {
            Reading = resp.Data.std_sum
            console.log('duizhou')
          } else {
            Reading = 0
          }
          this.listMeter.push({
            MeterId: row.MeterId,
            CardNo: row.CardNo,
            BarCode: row.BarCode,
            CustomerName: row.CustomerName,
            Address: row.Address,
            LastReading: res.Data ? res.Data.ThisRead : 0,
            Reading: Reading,
            LastBalanceEndTime: res.Data ? res.Data.BalanceEndTime : moment().format('YYYY-MM-DD HH:mm'),
            BalanceEndTime: moment().format('YYYY-MM-DD HH:mm')
          })
          this.$notify({
            title: '',
            message: '添加成功',
            duration: 800
          });
          // 去重复
          let hasObj= {};
          this.listMeter = this.listMeter.reduce((cur,next) => {
            // true && cur.push(next)惰性求值？--如果最后一个表达式为非false，那么直接返回这个表达式的结果，反之直接是false
            hasObj[next.MeterId] ? "" : (hasObj[next.MeterId] = true && cur.push(next)); 
            return cur;
          },[]) //设置cur默认类型为数组，并且初始值为空的数组
        })
        
      })
    },
    // 设置单个抄表数据
    setMeterParamsPopup(row) {
      this.dialogFormMeterParams = true
      this.tempMeterParams = row
    },
    // 删除某个抄表数据
    deleteMeterParams(row) {
      this.listMeter.forEach((item,index) => {
        if(item.MeterId === row.MeterId){
          this.listMeter.splice(index,1)
        }  
      })
    },
    editMeterParams() {
      for (let i = 0; i < this.listMeter.length; i ++) {
        if (this.tempMeterParams.MeterId === this.listMeter[i].MeterId) {
          this.listMeter[i] = this.tempMeterParams
          this.$message({
            message: '设置成功',
            type: 'success'
          })
          this.dialogFormMeterParams = false
          return
        }
      }
    },
    // 批量结算 创建任务
    AddBatchBalanceTask() {
      if (this.listMeter.length === 0) {
        this.$message({
          message: '请选择要抄表的表信息',
          type: 'error'
        })
      }
      this.$refs['dataForm_Batch'].validate((valid) => {
        if (valid) {
          let arr = this.listMeter
          arr.forEach((ele,index) => {
            delete ele.CardNo
            delete ele.CustomerName
            delete ele.Address
          })
          // 管输气
          if (this.temp.PriceType1 == 3) {
            this.temp.PriceNo1 = ''
            this.temp.PriceParam1.Price1 = 0
            this.temp.PriceParam1.Price2 = 0
            this.temp.PriceParam1.Price3 = 0
            this.temp.PriceParam1.Price4 = 0
            this.temp.PriceParam1.Price5 = 0
            this.temp.PriceParam1.Ladder1 = 0
            this.temp.PriceParam1.Ladder2 = 0
            this.temp.PriceParam1.Ladder3 = 0
            this.temp.PriceParam1.Ladder4 = 0
          } else if (this.temp.PriceType1 == 2){
            this.temp.PriceNo1 = ''
            this.temp.PriceParam1.Price1 = this.temp.PriceParam1.Price1 ? this.temp.PriceParam1.Price1 : 0
            this.temp.PriceParam1.Price2 = this.temp.PriceParam1.Price2 ? this.temp.PriceParam1.Price2 : 0
            this.temp.PriceParam1.Price3 = this.temp.PriceParam1.Price3 ? this.temp.PriceParam1.Price3 : 0
            this.temp.PriceParam1.Price4 = this.temp.PriceParam1.Price4 ? this.temp.PriceParam1.Price4 : 0
            this.temp.PriceParam1.Price5 = this.temp.PriceParam1.Price5 ? this.temp.PriceParam1.Price5 : 0
            this.temp.PriceParam1.Ladder1 = this.temp.PriceParam1.Ladder1 ? this.temp.PriceParam1.Ladder1 : 0
            this.temp.PriceParam1.Ladder2 = this.temp.PriceParam1.Ladder2 ? this.temp.PriceParam1.Ladder2 : 0
            this.temp.PriceParam1.Ladder3 = this.temp.PriceParam1.Ladder3 ? this.temp.PriceParam1.Ladder3 : 0
            this.temp.PriceParam1.Ladder4 = this.temp.PriceParam1.Ladder4 ? this.temp.PriceParam1.Ladder4 : 0
          } else if (this.temp.PriceType1 == 1) {
            this.temp.PriceParam1.Price1 = 0
            this.temp.PriceParam1.Price2 = 0
            this.temp.PriceParam1.Price3 = 0
            this.temp.PriceParam1.Price4 = 0
            this.temp.PriceParam1.Price5 = 0
            this.temp.PriceParam1.Ladder1 = 0
            this.temp.PriceParam1.Ladder2 = 0
            this.temp.PriceParam1.Ladder3 = 0
            this.temp.PriceParam1.Ladder4 = 0
          }

          let Parameter = {
            ...this.temp,
            BalanceParam: JSON.stringify(this.listMeter),
            PriceParam1: JSON.stringify(this.temp.PriceParam1),
            MeterCount: this.listMeter.length,
            BalanceState: 1,
            PriceType1: parseInt(this.temp.PriceType1),
            ExtData: '{}',
            Result: '[{}]'
          }

          AddBatchBalanceTask(Parameter).then(res => {
            if (res.State === 'success') {
              this.$message({
                message: '抄表任务创建成功',
                type: 'success'
              })
              this.dialogFormBatch = false
              this.resetTemp()
              this.getList()
            }
          })
        }
      })
    },
    // 获取抄表任务
    getList(init) {
      if (init === 'search') {
        this.Parameter.PageIndex = 1
        this.conModelCopy = {}
        this.conModelCopy.SearchKey = this.conModel.SearchKey
        this.conModelCopy.State = this.conModel.State
      }
      if (init === 'time') {
        this.conModelCopy.SearchKey = this.conModel.SearchKey
        this.conModelCopy.State = this.conModel.State
      }
      if (this.conModel.StartTime !== null && this.conModel.StartTime !== '' && (init === 'search' || init === 'time')) {
        this.conModelCopy.StartTime = moment(this.conModel.StartTime).format('YYYY-MM-DD HH:mm')
      }
      if (this.conModel.EndTime !== null && this.conModel.EndTime !== '' && (init === 'search' || init === 'time')) {
        this.conModelCopy.EndTime = moment(this.conModel.EndTime).format('YYYY-MM-DD HH:mm')
      }
      this.listLoading = true
      var Parameter = {
        ...this.Parameter,
        ...this.conModelCopy
      }
      this.listLoading = true
      GetBatchBalanceTask(Parameter).then(res => {
        this.listMeterTask = res.Data
        this.total = res.Total
        this.listLoading = false
      })
    },
    // 执行抄表任务2 撤销6 重新执行
    executeTasks(row) {
      let Parameter = {
        ...this.tempTasks
        // ...row.p,
        // BalanceState: 2
      }
      AddBatchBalanceTask(Parameter).then(res => {
        if (res.State === 'success') {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getList()
          this.tasksText = ''
          this.dialogVisibleExecute = false
        }
      })
    },
    // 删除弹窗
    DeleteBatchBalanceTaskPopup(row) {
      this.dialogVisibleTaskDelete = true
      this.taskDelete = row.p.Id
    },
    // 删除抄表任务
    DeleteBatchBalanceTask() {
      DeleteBatchBalanceTask( {SearchKey: this.taskDelete} ).then(res => {
        if (res.State === 'success') {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList()
          this.taskDelete = ''
          this.dialogVisibleTaskDelete = false
        }
      })
    },
    BalanceState(val) {
      switch (val) {
        case 1:
          return '已创建'
        case 2:
          return '待执行'
        case 3:
          return '结算中'
        case 4:
          return '结算完成'
        case 5:
          return '执行失败'
        case 6:
          return '已撤销'
        default:
          return '其他'
      }
    },
    // 获取铭牌号
    getBarCode(item) {
      let arr = JSON.parse(item)
      let barArr = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].BarCode) {
          barArr.push(arr[i].BarCode)
        }
      }
      return barArr.join(',')
    },
    // 查看结果
    resulePopup(row) {
      // console.log(row.p.Result)
      // let state = JSON.parse(row.p.Result.IsSuccess)
      // console.log(state)
      this.priceText = '价格1: ' + JSON.parse(row.p.PriceParam1).Price1 + ', ' + '阶梯1:' + JSON.parse(row.p.PriceParam1).Ladder1 + ', ' + '价格2:' + JSON.parse(row.p.PriceParam1).Price2 + ',' +'阶梯2:' + JSON.parse(row.p.PriceParam1).Ladder2 + ', ' +'价格3: ' + JSON.parse(row.p.PriceParam1).Price3 + ', ' +'阶梯3: ' + JSON.parse(row.p.PriceParam1).Ladder3 + ', ' +'价格4: ' + JSON.parse(row.p.PriceParam1).Price4 + ', ' +'阶梯4: ' + JSON.parse(row.p.PriceParam1).Ladder4 + ', ' +'价格5: ' + JSON.parse(row.p.PriceParam1).Price5
      this.listResult = []
      if (row.p.Result === '{}') {
        this.$message({
          message: '暂无结果,请稍后查看',
          type: 'info'
        })
        return
      }
      this.dialogFormResult = true
      let arr = JSON.parse(row.p.Result).sort(compare)
      let meterArr = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].BarCode) {
          meterArr.push(arr[i].MeterId)
        }
      }
      let meterID =  meterArr.join(',')
      let Parameter = {
        SearchKey: meterID,
        PageSize: 10,
        PageIndex: 1,
        OrderBy: '',
        isDesc: true
      }
      GetMeterInfoByID(Parameter).then(res => {
        let list = res.Data
        for (let i = 0; i < list.length; i++) {

          console.log(arr[i])
          if (arr[i].IsSuccess) {
            list[i].Message = '结算完成'
          } else {
            list[i].Message = arr[i].Message ? arr[i].Message : '暂无'
          }
        }
        this.listResult = list
      })

    },
    // 编辑
    EditBatchBalanceTask(row) {
      this.dialogFormBatch = true
      this.GetPricePlan()
      this.listMeter = []
      this.resetTemp()
      this.listMeter = JSON.parse(row.p.BalanceParam)
      this.temp.AccPeriod = row.p.AccPeriod
      this.temp.PriceType1 = String(row.p.PriceType1)
      this.temp.PriceNo1 = row.p.PriceNo1
      this.temp.PriceParam1 = JSON.parse(row.p.PriceParam1)
      this.temp.Id = row.p.Id
    },
    // 执行 撤销弹窗 
    executeTasksPopup(row,type) {
      if (type == 2) {
        this.tasksText = '是否执行任务?'
      } else {
        this.tasksText = '是否撤销任务?'
      }
      this.dialogVisibleExecute = true
      this.tempTasks = {
        ...row.p,
        BalanceState: type
      }
    },
    resetTemp() {
      this.temp = {
        Id: 0,
        BalanceType: 2, // 结算类型 1后付费2预付费
        AccPeriod: '', // 账期
        PriceType1: '', // 管输气价格类型
        PriceNo1: '', // 管输气指定的价格方案编号
        PriceParam1: { // 管输气自定义的价格参数
          Price1: 0,
          Price2: 0,
          Price3: 0,
          Price4: 0,
          Price5: 0,
          Ladder1: 0,
          Ladder2: 0,
          Ladder3: 0,
          Ladder4: 0
        },
        MeterCount: '', // 表计数量
        BalanceParam: '', // 结算参数  添加的表计信息
        BalanceState: '', // 结算状态 1已创建2待执行3结算中4结算完成5执行失败6已撤销
      }
    }
  }
}
</script>

<style>
.info .el-form-item {
  margin-bottom: 0px;
}

.set_popup .el-dialog__body {
  padding: 0px;
}

/* 价格 */
.price {
  margin-bottom: 8px !important;
}

/* input单位 */
.el-input-group__append, .el-input-group__prepend {
  padding: 0 5px;
}

.batch_btn {
  margin-left: 15px;
  width: 115px;
  height: 30px;
  line-height: 7px;
  font-size: 14px;
  color: #fff;
  background-color: #165DFF;
}

.batch_title_pupop {
  display: inline-block;
  margin: 0 15px;
}

.batch_popup .sel_btn {
  float: right;
  margin-right: 15px;
  margin-bottom: 10px;
  height: 30px;
  line-height: 7px;
  color: #fff;
  background: #165DFF;
}

.return_btn {
  float: right;
  margin-top: 10px;
  margin-right: 15px;
  margin-bottom: 10px;
  height: 38px;
  line-height: 7px;
  color: #fff;
  background: #165DFF;
}

.execute_btn {
  margin-top: 10px;
  margin-right: 0px;
}

.batch_tips {
  color: red;
  margin: 8px 0px 8px 15px;
}


</style>

